package info.motteke.util.net;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;

public class HttpClient {

    private String lastRequestUrl;

    private Proxy proxy;

    public HttpClient() {
        this(Proxy.NO_PROXY);
    }

    public HttpClient(Proxy proxy) {
        this.proxy = proxy;
    }

    public HttpResponse get(GetRequest request) throws IOException {
        URL url = buildUrl(request.getUrl());

        HttpURLConnection con = (HttpURLConnection)url.openConnection(proxy);
        con.setRequestMethod("get");

        boolean errorResponse = false;

        try {
            con.connect();
        } catch (IOException e) {
            if (!isServerError(con.getResponseCode())) {
                throw e;
            }
            errorResponse = true;
        }

        return new HttpResponse(con, errorResponse);
    }

    private boolean isServerError(int statusCode) {
        return 400 <= statusCode && statusCode < 600;
    }

    private URL buildUrl(String url) throws MalformedURLException {
        String createdUrl;

        if (url.indexOf("://") != -1) {
            createdUrl = url;
        } else if (url.startsWith("/")) {
            String domain = getLastAccessedDomain();
            createdUrl = domain + url;
        } else {
            String directory = getLastAccessedDirectory();
            createdUrl = directory + url;
        }

        URL ret = new URL(createdUrl);
        lastRequestUrl = createdUrl;
        return ret;
    }

    private String getLastAccessedDirectory() {
        if (isFirstAccess()) {
            throw new IllegalArgumentException("前回アクセスしたURLが存在しないため、相対URLを利用できません。");
        }

        return lastRequestUrl.replaceAll("([^/]+://[^/]+)/.*", "$1");
    }

    private String getLastAccessedDomain() {
        if (isFirstAccess()) {
            throw new IllegalArgumentException("前回アクセスしたURLが存在しないため、相対URLを利用できません。");
        }
        int index = lastRequestUrl.lastIndexOf('/');
        return lastRequestUrl.substring(0, index - 1);
    }

    private boolean isFirstAccess() {
        return lastRequestUrl == null;
    }
}
